<template>
  <div class="xinxi">
    <img class="top" src="../assets/images/message/top.png" alt="">
    <div class="bot">
      <el-form label-position="left" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px">

        <div class="form">
          <img src="../assets/images/message/昵称icon.png" alt="">
          <el-form-item class="itemform" label="昵称" prop="name">
            <el-input v-model="ruleForm.userName" @blur="getInput" maxlength="5"></el-input>
          </el-form-item>
        </div>
        <div class="form">
          <img class="sfz" src="../assets/images/message/身份证icon.png" alt="">
          <el-form-item class="itemform" label="身份证号" prop="userCardId">
            <el-input v-model="ruleForm.userCardId" @blur="getInput"></el-input>
          </el-form-item>
        </div>
        <div class="form">
          <img src="../assets/images/message/性别icon.png" alt="">
          <el-form-item class="itemform" label="性别" prop="sex">
            <!-- <el-radio-group v-model="ruleForm.sex">
              <el-radio :label="0">男</el-radio>
              <el-radio :label="1">女</el-radio>
            </el-radio-group> -->
            <!-- <el-select v-model="ruleForm.sex" placeholder="请选择性别">
              <el-option label="男" value="0"></el-option>
              <el-option label="女" value="1"></el-option>
            </el-select> -->
            <div class="sex">
              <van-field readonly clickable name="picker" :value="sex" placeholder="请选择性别" @click="showPicker = true"
                input-align="right" />
              <van-popup v-model="showPicker" position="bottom">
                <van-picker title="请选择您的性别" confirm-button-text="完成" show-toolbar :columns="columns" @confirm="onConfirm"
                  @cancel="showPicker = false" />
              </van-popup>
              <img src="../assets/images/message/jt.png" alt="">
            </div>

          </el-form-item>
        </div>
        <div class="text"> 您的数据会脱敏处理，我们将保护您的隐私安全 </div>


        <!-- <el-form-item label="年龄" prop="age" >
          <el-input v-model="ruleForm.age" disabled></el-input>
        </el-form-item>
        <el-form-item label="教育程度" prop="education">
          <el-select v-model="ruleForm.education" placeholder="请选择教育程度">
            <el-option label="小学及以下" value="0"></el-option>
            <el-option label="初中" value="2"></el-option>
            <el-option label="高中" value="3"></el-option>
            <el-option label="大专" value="4"></el-option>
            <el-option label="本科" value="5"></el-option>
            <el-option label="硕士" value="6"></el-option>
            <el-option label="博士" value="7"></el-option>
          </el-select>
        </el-form-item> -->

      </el-form>
    </div>
    <div class="txk" v-show="show">
      <img src="../assets/images/message/txk-silver.png" alt="">
    </div>
    <div class="txk" v-show="!show" @click="submitForm('ruleForm')">
      <img src="../assets/images/message/txk-gold.png" alt="">
    </div>
    <div class="but" @click="submitForm('ruleForm')">
      <img src="../assets/images/message/lingqu.png" alt="">
    </div>

  </div>
</template>
<script>
import axios from "axios";
import api from "@/api";
import Cookies from 'js-cookie'
import { info, submit, userinfo1, addpacketstep, currentpacketstep,addburyingpoint } from '@/api/http.js'
import config from "../config/index.js";
import {
  getUrl
} from "@/config.js";
import { Toast } from "vant";
export default {
  props: {

  },
  data() {
    return {
      data: {},
      imgUrl: "",
      mechanismMemberUserId: "",
      phone: '',
      show: true,
      columns: ['男', '女'],
      showPicker: false,
      sex: '',
      ruleForm: {
        userName: '',
        userCardId: '',
        age: '',
        education: '',
        delivery: false,
        type: [],
        sex: '',
        desc: '',
      },
      rules: {
        userName: [
          //   // { required: true, message: '请输入名称', trigger: 'blur' },
          { validator: this.nick, trigger: 'blur' }
          //   { required: true, message: '请输入姓名', trigger: 'blur' },
          //   { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        userCardId: [
          // { required: true, message: "请输入身份证号", trigger: "blur" },
          { validator: this.idcard, trigger: "blur" },

        ],
        birthday: [{ required: true, message: '请输入身份证自动获取出生日期', trigger: ['change'] }],
        // sex: [{ required: true, message: '请选择性别' }]
        // education: [{ required: true, message: '请选择教育程度', trigger: 'blur'}],
      }

    };
  },
  created() {
    this.sex = '男'
  },
  methods: {
    // 选择性别
    onConfirm(value, index) {
      console.log('===性别===', value, index);
      this.sex = value;
      this.sexIndex = index
      this.showPicker = false;
    },
    // 判断昵称
    nick(str) {
      console.log('输入===', str);
      const reg = /[\u4e00-\u9fa5]/g; // 匹配中文字符的正则表达式
      const len = str.replace(reg, 'aa').length; // 将中文字符替换为两个英文字符，再计算长度
      const containsNumber = /\d/.test(str); // 判断是否包含数字
      if (len > 10) {
        Toast('昵称不能超过10个字符');
        return
      } else if (containsNumber) {
        Toast('昵称不能包含数字');
        return
      } else if (str == '') {
        Toast('昵称不能为空');
        return
      } else {
        // this.userName = this.message
        // this.isName = false
        console.log('userName', this.ruleForm.userName);
      }
    },
    getaddpacketstep() {
      let url = encodeURIComponent('message?path=onebasicinformation')
      addpacketstep(url).then(res => {
        console.log(res)
      })
    },
    // getcurrentpacketstep(){
    //   currentpacketstep().then(res=>{
    //     console.log(res)
    //   })
    // },
    specialScript(str) {
      var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]");
      return pattern.test(str);
    },

    getData() {
      var baseUrl = getUrl();
      var phone = ''
      var token = localStorage.getItem('token')
      info({
        phone: this.phoneInfo,
        isSuggest: 3
      }).then(res => {
        console.log(res)
        const userInfo = res.rows[0];
        console.log(userInfo);
        // 
        this.ruleForm.userName = userInfo.nickName
        this.ruleForm.userCardId = userInfo.userCardId
        // this.ruleForm.sex = userInfo.sex
        if(userInfo.sex == '1'){
          this.sex = '女'
        }else{
          this.sex = '男'
        }
        // this.ruleForm.education = userInfo.education
        // this.ruleForm.age = userInfo.age
        console.log('this.ruleForm.userName',this.ruleForm.userName,this.ruleForm.userCardId,this.sex);
        if(this.ruleForm.userName !== null || this.ruleForm.userCardId !== null){
          this.show = false
        }
        this.phone = userInfo.phone
        console.log(phone);
        // if (res.data.code == 200) {

        //   // debugger
        //   // localStorage.setItem("token", res.data.data.token);
        //   // this.$router.push('/activity')
        // } else {
        //   // this.$message.error('信息获取失败！');
        // }
      })
      // axios.get(
      //   baseUrl + "/an/wechat_app/wechat_user/info?token=" + token,
      //   // `https://www.ainaoxingdong.com/api/an/wechat_app/wechat_user/report/bind_img?token=${_this.token}`,
      // {
      //   phone: this.phoneInfo,
      //   isSuggest: 3
      // }
      // ).then((res) => {
      //   const userInfo = res.data.rows[0];
      //   console.log(userInfo);

      //   this.ruleForm.userName = userInfo.userName
      //   this.ruleForm.userCardId = userInfo.userCardId
      //   this.ruleForm.sex = userInfo.sex
      //   // this.ruleForm.education = userInfo.education
      //   // this.ruleForm.age = userInfo.age

      //   this.phone = userInfo.phone
      //   console.log(phone);
      //   if (res.data.code == 200) {

      //     // 
      //     // localStorage.setItem("token", res.data.data.token);
      //     // this.$router.push('/activity')
      //   } else {
      //     // this.$message.error('信息获取失败！');
      //   }
      // });
    },
    async idcard(rule, value, callback) {
      if (!value) {
        if (rule.field == "id") {
          return callback(new Error("身份证号码不能为空"));
        } else {
          return;
        }
      } else {
        var num = value.charAt(16);
        console.log('数字', num);
        if (num % 2 == 0) {
          console.log(num)
          this.ruleForm.sex = 0
        } else {
          this.ruleForm.sex = 1
        }
        localStorage.setItem('sex', this.ruleForm.sex)
      }
      //setTimeout(() => {
      let regIdCard = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;
      //如果通过该验证，说明身份证格式正确，但准确性还需计算
      if (regIdCard.test(value)) {
        await this.go(value.length);
        if (value.length == 18) {
          var idCardWi = new Array(
            7,
            9,
            10,
            5,
            8,
            4,
            2,
            1,
            6,
            3,
            7,
            9,
            10,
            5,
            8,
            4,
            2
          ); //将前17位加权因子保存在数组里
          var idCardY = new Array(1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2); //这是除以11后，可能产生的11位余数、验证码，也保存成数组
          var idCardWiSum = 0; //用来保存前17位各自乖以加权因子后的总和
          for (var i = 0; i < 17; i++) {
            idCardWiSum += value.substring(i, i + 1) * idCardWi[i];
          }
          var idCardMod = idCardWiSum % 11; //计算出校验码所在数组的位置
          var idCardLast = value.substring(17); //得到最后一位身份证号码
          //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
          if (idCardMod == 2) {
            if (idCardLast == "X" || idCardLast == "x") {
              callback();
            } else {
              callback(new Error("身份证号码错误"));
            }
          } else {
            //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
            if (idCardLast == idCardY[idCardMod]) {
              callback();
            } else {
              callback(new Error("身份证号码错误"));
            }
          }
        }
      } else {
        callback(new Error("身份证格式不正确"));
      }
      //}, 1000);
    },
    go(val) {
      let iden = this.ruleForm.userCardId;
      let sex = null;
      let birth = null;
      let myDate = new Date();
      let month = myDate.getMonth() + 1;
      let day = myDate.getDate();
      let age = 0;
      if (val === 18) {
        age = myDate.getFullYear() - iden.substring(6, 10) - 1;
        sex = iden.substring(16, 17);
        birth = iden.substring(6, 10) + "-" + iden.substring(10, 12) + "-" + iden.substring(12, 14);
        if (iden.substring(10, 12) < month || iden.substring(10, 12) == month && iden.substring(12, 14) <= day) age++;

      }
      if (val === 15) {
        age = myDate.getFullYear() - iden.substring(6, 8) - 1901;
        sex = iden.substring(13, 14);
        birth = "19" + iden.substring(6, 8) + "-" + iden.substring(8, 10) + "-" + iden.substring(10, 12);
        if (iden.substring(8, 10) < month || iden.substring(8, 10) == month && iden.substring(10, 12) <= day) age++;
      }

      this.ruleForm.age = age;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.ruleForm.userName.length > 5) {
            Toast('昵称不能超过5个字')
            return;
          }
          if (this.specialScript(this.ruleForm.userName)) {
            Toast('昵称包含特殊字符')
            return;
          }
          const containsNumber = /\d/.test(this.ruleForm.userName);
          if (containsNumber) {
            Toast('昵称不能包含数字');
            return;
          }

          let obj = {}
          obj.nickName = this.ruleForm.userName
          if (this.sex == '女') {
            obj.sex = '1'
          } else {
            obj.sex = '0'
          }
          obj.userCardId = this.ruleForm.userCardId

          console.log('obj', obj);
          userinfo1(obj).then(res => {
            console.log('userinfo1', res)
            if(res.code == 500){
              Toast(res.msg)
            }else{
              let obj = { buriedPointName: '获取提现卡', section: '4', module: '1', function: '2', redirectPage: '提现卡点亮页', orgNo: '' }
              addburyingpoint(obj).then(res => {
                  console.log(res)
              })
              this.$router.push('/onebasicinformation')
            }
            
          })
        } else {
          Toast('请检查填写信息')
        }

      })
      // if (this.ruleForm.userName.length > 5) {
      //   Toast('名称长度不能超过5个字')
      //   return;
      // }
      // if (this.specialScript(this.ruleForm.userName)) {
      //   this.$message.error('包含特殊字符')
      //   return;
      // }



      // this.$refs[formName].validate((valid) => {
      //   if (valid) {
      //     const params = JSON.parse(JSON.stringify(this.ruleForm));
      //     console.log(params, '我的')
      //     var baseUrl = getUrl();
      //     var token = localStorage.getItem("token");
      //     params.marriage = 0
      //     params.occupation = 0
      //     // params.education = this.ruleForm.education
      //     params.phone = this.phone
      //     submit(params).then(res => {
      //       console.log(res)
      //       Cookies.set("doctorId", res.data.doctorId);
      //       Cookies.set("token", res.data.token);
      //       Cookies.set("patientId", res.data.patientId);
      //       Cookies.set("patientVersion", 1);
      //       console.log(config.groupId)
      //       Cookies.set("groupId", config.groupId);
      //       localStorage.setItem('userinfo', JSON.stringify(res.data))
      //       let params = { groupId: config.groupId }
      //       api.getMemoryInfoById(params).then(res => {
      //         console.log(res)
      //         if (res.code == 1) {
      //           console.log(res);
      //           this.assessCount = res.data.assessCount;
      //           this.continueTodo = res.data.continueTodo;
      //           this.nextRoute = res.data.nextRoute;
      //           if (this.continueTodo != 0) {
      //             Cookies.set("patientId", res.data.patientId);
      //           } else {
      //             Cookies.set("masterId", res.data.uuid);
      //             // Cookies.set("patientId", '');
      //           }
      //           Cookies.set("groupId", res.data.groupId);
      //         }
      //       })
      //       const {
      //         data
      //       } = res
      //       // 
      //       this.data = data.data || {}
      //       // console.log('data123', res.data.data.url)
      //       // location.href = (res.data.data.url)
      //       console.log(res.data.doctorId)

      //     })
      //     // axios.post(
      //     //   baseUrl + "/an/wechat_app/wechat_user/submit?token=" + token,
      //     //   params
      //     // ).then((res) => {
      //     //   const {
      //     //     data
      //     //   } = res
      //     //   // 
      //     //   this.data = data.data || {}
      //     //   console.log('data123', res.data.data.url)
      //     //   location.href = (res.data.data.url)
      //     // });

      //   } else {
      //     this.$message.error('请检查填写信息！')
      //     return false;
      //   }
      // });

    },

    // getinfo(){
    //   let obj = {sex:0,age:25,marriage:0,occupation:0,phone:13946990741,education:0}
    //   info(obj).then(res=>{
    //     console.log(res)
    //   })
    // },
    // submitForm(){
    //   this.getinfo()
    // }
    getInput() {
      console.log('userName', this.ruleForm.userName, this.ruleForm.userCardId);
      if (this.ruleForm.userName == null || this.ruleForm.userCardId == null) {
        console.log('1');
        this.show = true
      } else if (this.ruleForm.userName == '' || this.ruleForm.userCardId == '') {
        console.log('2');
        this.show = true
      } else {
        console.log('3');
        this.show = false
      }
    }

  },
  mounted() {
    this.getData()
    this.getaddpacketstep()
    // this.getcurrentpacketstep()
  },
};
</script>

<style lang="scss">
.form {
  width: 332px;
  height: 48px;
  display: flex;
  background: #FFFFFF;
  border-radius: 24px;
  display: flex;
  align-items: center;
  margin-bottom: 20px;

  img {
    width: 17px;
    height: 17px;
    margin-left: 20px;
  }

  .sfz {
    width: 19px;
    height: 14px;
  }
}

.itemform {
  width: 85%;
  // background: #fff;
  margin: auto;
  // margin-top: 10px;
  // padding: 5px 10px;
  // display: ;

  text-align: left;

  input {
    border: none;

  }
}

.el-form {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.xinxi {
  width: 100%;
  height: 100%;
  background-color: #F9F9F9;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.top {
  width: 100%;
}

.bot {
  width: 100%;
  // padding: 20px;
  margin-top: -40px;
  // border-radius: 30px;
  position: relative;
  z-index: 111;
}

.but {
  width: 100%;
  // margin-top: 50px;
  position: absolute;
  bottom: 20px;
  text-align: center;

  img {
    width: 100%;
  }
}

.txk {
  width: 190px;
  height: 125px;
  margin: 40px 0;

  img {
    width: 100%;
  }
}

.el-button--medium {
  width: 70%;
  height: 50px;
  border-radius: 10px;
  font-size: 20px;
}

.text {
  margin-top: 5px;
  font-size: 12px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #999999;
}

.tipText {
  height: 10px;
  color: gray;
  text-align: center;
  font-size: 20px;
  margin-bottom: 20px;
}

.sex {
  display: flex;
  align-items: center;
  // background-color: aqua;

  img {
    width: 9px;
    height: 16px;
    margin-right: 5px;
  }
}

.van-cell {
  padding: 6px 15px;
  margin-right: -20px;
}

.van-field::after {
  border-bottom: none;
}

.el-form-item__error {
  top: 115%;
}
.el-input__inner{
  text-align: right;
}
</style>
